package com.example.mylock;

/**
 * description: MyReentrantLock <br>
 * date: 2021/3/1 10:42 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
public class MyReentrantLock {

    private boolean isLock = false;

    // 用于记录是不是重入的线程
    private Thread lockOwner = null;

    // 累计加锁次数，加锁一次+1 解锁一次-1
    private int lockedCount = 0;

    public synchronized void lock() throws InterruptedException {
        Thread thread = Thread.currentThread();

        System.out.println("进入lock方法上锁"+thread.getName());

        // 判断是否是同个线程获取锁 地址比较
        while (isLock && lockOwner != thread){
            System.out.println("当前有人持有锁，进入wait等待"+Thread.currentThread().getName());
            System.out.println("当前锁状态 isLock = "+isLock);
            System.out.println("当前count数量 lockedCount = "+lockedCount);
            wait();
        }
        isLock = true;
        lockOwner = thread;
        lockedCount++;

    }

    public synchronized void unlock(){
        Thread thread = Thread.currentThread();

        System.out.println("进入unLock方法解锁"+Thread.currentThread().getName());

        // 线程A加的锁 只能线程A解锁
        if (thread == this.lockOwner){
            lockedCount--;
            if (lockedCount == 0){
                isLock = false;
                lockOwner = null;
                notify();
            }
        }

    }

}
